package com.aiguigu.lottery.prize.controller;

import com.aiguigu.lottery.common.entity.PrizeEntity;
import com.aiguigu.lottery.common.entity.PrizeRecordEntity;
import com.aiguigu.lottery.common.entity.UserEntity;
import com.aiguigu.lottery.common.utils.JwtUtils;
import com.aiguigu.lottery.prize.service.PrizeService;
import com.aiguigu.lottery.prize.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/prizes")
@CrossOrigin(origins = "*")
public class PrizeController {
    
    private static final Logger logger = LoggerFactory.getLogger(PrizeController.class);
    
    @Autowired
    private PrizeService prizeService;
    
    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    @Autowired
    private JwtUtils jwtUtils;
    
    @Autowired
    private UserMapper userMapper;
    
    /**
     * 创建奖品（仅job=1的用户可操作）
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createPrize(
            @RequestBody PrizeEntity prize,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 从token中获取用户名
            String username = jwtUtils.getUsernameFromToken(token.replace("Bearer ", ""));
            if (username == null) {
                response.put("code", 0);
                response.put("msg", "无效的token");
                return ResponseEntity.ok(response);
            }
            
            boolean success = prizeService.createPrizeByUsername(prize, username);
            if (success) {
                response.put("code", 1);
                response.put("msg", "奖品创建成功");
            } else {
                response.put("code", 0);
                response.put("msg", "权限不足或创建失败");
            }
        } catch (Exception e) {
            response.put("code", 0);
            response.put("msg", "创建奖品失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 更新奖品（仅job=1的用户可操作）
     */
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updatePrize(
            @PathVariable Integer id,
            @RequestBody PrizeEntity prize,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = jwtUtils.getUsernameFromToken(token.replace("Bearer ", ""));
            if (username == null) {
                response.put("code", 0);
                response.put("msg", "无效的token");
                return ResponseEntity.ok(response);
            }
            
            prize.setId(id);
            boolean success = prizeService.updatePrizeByUsername(prize, username);
            if (success) {
                response.put("code", 1);
                response.put("msg", "奖品更新成功");
            } else {
                response.put("code", 0);
                response.put("msg", "权限不足或更新失败");
            }
        } catch (Exception e) {
            response.put("code", 0);
            response.put("msg", "更新奖品失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 删除奖品（仅job=1的用户可操作）
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deletePrize(
            @PathVariable Integer id,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = jwtUtils.getUsernameFromToken(token.replace("Bearer ", ""));
            if (username == null) {
                response.put("code", 0);
                response.put("msg", "无效的token");
                return ResponseEntity.ok(response);
            }
            
            boolean success = prizeService.deletePrizeByUsername(id, username);
            if (success) {
                response.put("code", 1);
                response.put("msg", "奖品删除成功");
            } else {
                response.put("code", 0);
                response.put("msg", "权限不足或删除失败");
            }
        } catch (Exception e) {
            response.put("code", 0);
            response.put("msg", "删除奖品失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取所有启用的奖品
     */
    @GetMapping("/enabled")
    public ResponseEntity<Map<String, Object>> getEnabledPrizes() {
        List<PrizeEntity> prizes = prizeService.getAllEnabledPrizes();
        
        Map<String, Object> response = new HashMap<>();
        response.put("code", 1);
        response.put("msg", "获取启用的奖品成功");
        response.put("data", prizes);
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取所有启用的奖品 - 前端抽奖页面使用
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getPrizeList() {
        List<PrizeEntity> prizes = prizeService.getAllEnabledPrizes();
        
        // 转换为前端需要的格式
        List<Map<String, Object>> prizeList = new ArrayList<>();
        for (PrizeEntity prize : prizes) {
            Map<String, Object> prizeMap = new HashMap<>();
            prizeMap.put("id", prize.getId());
            prizeMap.put("name", prize.getName());
            prizeMap.put("image", prize.getImageUrl()); // 将imageUrl映射为image
            prizeMap.put("probability", prize.getProbability());
            prizeMap.put("points", 0); // 添加默认的points字段
            prizeMap.put("total", prize.getTotal() != null ? prize.getTotal() : 0); // 添加总数量
            prizeMap.put("remaining", prize.getRemaining() != null ? prize.getRemaining() : 0); // 添加剩余数量
            prizeList.add(prizeMap);
        }
        
        Map<String, Object> response = new HashMap<>();
        response.put("code", 1);
        response.put("msg", "获取奖品列表成功");
        response.put("data", prizeList);
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取所有奖品（仅job=1的用户可查看）
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getAllPrizes(
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = jwtUtils.getUsernameFromToken(token.replace("Bearer ", ""));
            if (username == null) {
                response.put("code", 0);
                response.put("msg", "无效的token");
                return ResponseEntity.ok(response);
            }
            
            // 检查用户权限
            UserEntity user = userMapper.findByUsername(username);
            if (user == null || user.getJob() != 1) {
                response.put("code", 0);
                response.put("msg", "权限不足");
                return ResponseEntity.ok(response);
            }
            
            List<PrizeEntity> prizes = prizeService.getAllPrizes();
            response.put("code", 1);
            response.put("msg", "获取所有奖品成功");
            response.put("data", prizes);
            
        } catch (Exception e) {
            response.put("code", 0);
            response.put("msg", "获取奖品失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 抽奖接口
     */
    @PostMapping("/draw")
    public ResponseEntity<Map<String, Object>> drawPrize(
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = jwtUtils.getUsernameFromToken(token.replace("Bearer ", ""));
            if (username == null) {
                response.put("code", 401);
                response.put("message", "无效的token");
                return ResponseEntity.ok(response);
            }
            
            // 获取用户信息
            UserEntity user = userMapper.findByUsername(username);
            if (user == null) {
                response.put("code", 0);
                response.put("msg", "用户不存在");
                return ResponseEntity.ok(response);
            }
            
            // 执行抽奖逻辑（包含库存检查和扣减）
            PrizeEntity wonPrize = prizeService.drawPrize(user.getId());
            
            if (wonPrize != null) {
                // 发送消息到队列
                PrizeRecordEntity record = new PrizeRecordEntity();
                record.setUserId(user.getId());
                record.setUsername(user.getUsername());
                record.setPrizeId(wonPrize.getId());
                record.setPrizeName(wonPrize.getName());
                record.setPrizeImage(wonPrize.getImageUrl());
                record.setCreateTime(new Date());
                
                rabbitTemplate.convertAndSend("prize.win.exchange", "prize.win.routing.key", record);
                
                // 转换为前端需要的格式
                Map<String, Object> prizeData = new HashMap<>();
                prizeData.put("id", wonPrize.getId());
                prizeData.put("name", wonPrize.getName());
                prizeData.put("image", wonPrize.getImageUrl()); // 将imageUrl映射为image
                prizeData.put("probability", wonPrize.getProbability());
                prizeData.put("total", wonPrize.getTotal());
                prizeData.put("remaining", wonPrize.getRemaining());
                
                response.put("code", 1);
                response.put("msg", "恭喜中奖！");
                response.put("data", prizeData);
                
                logger.info("用户 {} 中奖: {}, 剩余库存: {}", 
                           username, wonPrize.getName(), 
                           prizeService.checkPrizeStock(wonPrize.getId()));
            } else {
                response.put("code", 1);
                response.put("msg", "很遗憾，未中奖或奖品库存不足");
                response.put("data", null);
            }
            
        } catch (Exception e) {
            logger.error("抽奖失败", e);
            response.put("code", 0);
            response.put("msg", "抽奖失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 保存中奖记录
     */
    @PostMapping("/records/save")
    public ResponseEntity<Map<String, Object>> savePrizeRecord(
            @RequestBody Map<String, Object> recordData,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = jwtUtils.getUsernameFromToken(token.replace("Bearer ", ""));
            if (username == null) {
                response.put("code", 0);
                response.put("msg", "无效的token");
                return ResponseEntity.ok(response);
            }
            
            // 获取用户信息
            UserEntity user = userMapper.findByUsername(username);
            if (user == null) {
                response.put("code", 0);
                response.put("msg", "用户不存在");
                return ResponseEntity.ok(response);
            }
            
            // 创建中奖记录
            PrizeRecordEntity record = new PrizeRecordEntity();
            record.setUserId(user.getId());
            record.setUsername(user.getUsername());
            record.setPrizeId((Integer) recordData.get("prizeId"));
            record.setPrizeName((String) recordData.get("prizeName"));
            record.setCreateTime(new Date());
            
            boolean success = prizeService.savePrizeRecord(record);
            if (success) {
                response.put("code", 1);
                response.put("msg", "中奖记录保存成功");
            } else {
                response.put("code", 0);
                response.put("msg", "中奖记录保存失败");
            }
            
        } catch (Exception e) {
            logger.error("保存中奖记录失败", e);
            response.put("code", 0);
            response.put("msg", "保存中奖记录失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取用户的中奖记录
     */
    @GetMapping("/records/user")
    public ResponseEntity<Map<String, Object>> getUserPrizeRecords(
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = jwtUtils.getUsernameFromToken(token.replace("Bearer ", ""));
            if (username == null) {
                response.put("code", 0);
                response.put("msg", "无效的token");
                return ResponseEntity.ok(response);
            }
            
            List<PrizeRecordEntity> records = prizeService.getUserPrizeRecords(username);
            response.put("code", 1);
            response.put("msg", "获取用户中奖记录成功");
            response.put("data", records);
            
        } catch (Exception e) {
            response.put("code", 0);
            response.put("msg", "获取用户中奖记录失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取所有中奖记录（仅job=1的用户可查看）
     */
    @GetMapping("/records/all")
    public ResponseEntity<Map<String, Object>> getAllPrizeRecords(
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = jwtUtils.getUsernameFromToken(token.replace("Bearer ", ""));
            if (username == null) {
                response.put("code", 0);
                response.put("msg", "无效的token");
                return ResponseEntity.ok(response);
            }
            
            // 检查用户权限
            UserEntity user = userMapper.findByUsername(username);
            if (user == null || user.getJob() != 1) {
                response.put("code", 0);
                response.put("msg", "权限不足");
                return ResponseEntity.ok(response);
            }
            
            List<PrizeRecordEntity> records = prizeService.getAllPrizeRecords();
            response.put("code", 1);
            response.put("msg", "获取所有中奖记录成功");
            response.put("data", records);
            
        } catch (Exception e) {
            response.put("code", 0);
            response.put("msg", "获取所有中奖记录失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 检查用户权限
     */
    @GetMapping("/permission")
    public ResponseEntity<Map<String, Object>> checkPermission(
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = jwtUtils.getUsernameFromToken(token.replace("Bearer ", ""));
            if (username == null) {
                response.put("code", 0);
                response.put("msg", "无效的token");
                return ResponseEntity.ok(response);
            }
            
            UserEntity user = userMapper.findByUsername(username);
            if (user != null && user.getJob() == 1) {
                response.put("code", 1);
                response.put("msg", "有管理权限");
                response.put("data", true);
            } else {
                response.put("code", 1);
                response.put("msg", "无管理权限");
                response.put("data", false);
            }
            
        } catch (Exception e) {
            response.put("code", 0);
            response.put("msg", "检查权限失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取有库存的奖品列表
     */
    @GetMapping("/available")
    public ResponseEntity<Map<String, Object>> getAvailablePrizes() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<PrizeEntity> prizes = prizeService.getAvailablePrizes();
            response.put("code", 1);
            response.put("msg", "获取有库存的奖品成功");
            response.put("data", prizes);
        } catch (Exception e) {
            response.put("code", 0);
            response.put("msg", "获取有库存的奖品失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 检查奖品库存
     */
    @GetMapping("/{id}/stock")
    public ResponseEntity<Map<String, Object>> checkPrizeStock(
            @PathVariable Integer id) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            Integer stock = prizeService.checkPrizeStock(id);
            response.put("code", 1);
            response.put("msg", "获取奖品库存成功");
            response.put("data", stock);
        } catch (Exception e) {
            response.put("code", 0);
            response.put("msg", "获取奖品库存失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 更新奖品库存（仅job=1的用户可操作）
     */
    @PutMapping("/{id}/stock")
    public ResponseEntity<Map<String, Object>> updatePrizeStock(
            @PathVariable Integer id,
            @RequestBody Map<String, Object> stockData,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = jwtUtils.getUsernameFromToken(token.replace("Bearer ", ""));
            if (username == null) {
                response.put("code", 0);
                response.put("msg", "无效的token");
                return ResponseEntity.ok(response);
            }
            
            // 检查用户权限
            UserEntity user = userMapper.findByUsername(username);
            if (user == null || user.getJob() != 1) {
                response.put("code", 0);
                response.put("msg", "权限不足");
                return ResponseEntity.ok(response);
            }
            
            Integer total = (Integer) stockData.get("total");
            Integer remaining = (Integer) stockData.get("remaining");
            
            if (total == null || remaining == null) {
                response.put("code", 0);
                response.put("msg", "参数不完整");
                return ResponseEntity.ok(response);
            }
            
            if (remaining > total || remaining < 0 || total < 0) {
                response.put("code", 0);
                response.put("msg", "库存数据不合法");
                return ResponseEntity.ok(response);
            }
            
            boolean success = prizeService.updatePrizeStock(id, total, remaining);
            if (success) {
                response.put("code", 1);
                response.put("msg", "更新奖品库存成功");
            } else {
                response.put("code", 0);
                response.put("msg", "更新奖品库存失败");
            }
            
        } catch (Exception e) {
            response.put("code", 0);
            response.put("msg", "更新奖品库存失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 批量更新奖品库存（仅job=1的用户可操作）
     */
    @PutMapping("/stock/batch")
    public ResponseEntity<Map<String, Object>> batchUpdatePrizeStock(
            @RequestBody List<PrizeEntity> prizes,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = jwtUtils.getUsernameFromToken(token.replace("Bearer ", ""));
            if (username == null) {
                response.put("code", 0);
                response.put("msg", "无效的token");
                return ResponseEntity.ok(response);
            }
            
            // 检查用户权限
            UserEntity user = userMapper.findByUsername(username);
            if (user == null || user.getJob() != 1) {
                response.put("code", 0);
                response.put("msg", "权限不足");
                return ResponseEntity.ok(response);
            }
            
            // 验证数据
            for (PrizeEntity prize : prizes) {
                if (prize.getId() == null || prize.getTotal() == null || prize.getRemaining() == null) {
                    response.put("code", 0);
                    response.put("msg", "奖品数据不完整");
                    return ResponseEntity.ok(response);
                }
                
                if (prize.getRemaining() > prize.getTotal() || 
                    prize.getRemaining() < 0 || prize.getTotal() < 0) {
                    response.put("code", 0);
                    response.put("msg", "奖品ID " + prize.getId() + " 的库存数据不合法");
                    return ResponseEntity.ok(response);
                }
            }
            
            boolean success = prizeService.batchUpdatePrizeStock(prizes);
            if (success) {
                response.put("code", 1);
                response.put("msg", "批量更新奖品库存成功");
            } else {
                response.put("code", 0);
                response.put("msg", "批量更新奖品库存失败");
            }
            
        } catch (Exception e) {
            response.put("code", 0);
            response.put("msg", "批量更新奖品库存失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
}